<template>
  <div class="phone" id="phone" ref="phone">
    <Header
      :currentTalkObj="currentTalkObj"
      @fullScreen="fullScreen"
      @handleOpenMeeting="handleOpenMeeting"
      @handleClearConnection="handleClearConnection"
      @handleCallMake="handleCallMake"
    />
    <div style="width:99%">
      <div class="my_main">
        <div class="mid">
          <!-- 当前通话 div -->
          <div class="mid-left">
            <div class="mid-top">
              <div class="mess-left">
                <div class="call-item">{{$t('m.NAME')}}：{{currentTalkObj.realName}}</div>
                <div class="call-item">{{$t('m.PART')}}：{{currentTalkObj.groupName}}</div>
                <div class="call-item">{{$t('m.TIME')}}：{{currentTalkObj.talkTime}}</div>
              </div>
              <div class="mess-right">
                <div class="call-item">{{$t('m.TEL')}}：{{currentTalkObj.deviceTel}}</div>
                <div
                  class="call-item"
                >{{$t('m.STATUS')}}：{{this.getUserStatusBytel(currentTalkObj.deviceTel)}}</div>
              </div>
            </div>
            <div class="mid-bottom">
              <div class="call-button-div">
                <div style="float:right;">
                  <!-- 解除保持':'保持 按钮 -->
                  <el-button
                    type="primary"
                    icon="el-icon-phone-outline"
                    :disabled="!currentTalkObj.deviceTel"
                    @click="handleHoldCallBytel(currentTalkObj.deviceTel)"
                  >{{this.deviceStatusMap.get(currentTalkObj.deviceTel) == 'hold'?$t('m.HOLD_OFF'):$t('m.HOLD')}}</el-button>
                  <el-button
                    type="primary"
                    icon="el-icon-phone"
                    :disabled="!currentTalkObj.deviceTel"
                    @click="handleClearCall(currentTalkObj.deviceTel)"
                  >{{$t('m.HANG_UP')}}</el-button>
                </div>
              </div>
              <div class="transfer-button-div">
                <div style="float:right;margin-top:5%" v-if="currentTalkObj.consultForm">
                  <span class="transfer-tite">{{$t('m.CALL_TRANSFER')}}：</span>
                  <!-- 同意转接：拒接转接 -->
                  <el-button
                    type="primary"
                    icon="el-icon-check"
                    @click="handleTransferCallAfterConsult()"
                  >{{$t('m.AGREE_TO_TRANSFER')}}</el-button>
                  <el-button
                    type="primary"
                    icon="el-icon-close"
                    @click="handleClearAfterConsult()"
                  >{{$t('m.REJECT_TRANSFER')}}</el-button>
                </div>
              </div>
            </div>
          </div>
          <!-- 等待/保持列表 -->
          <div class="mid-right">
            <div class="mid-right-top">
              <div class="txt">{{$t('m.WAIT_LIST')}}</div>
              <!-- 等待列表 -->
              <el-table
                :data="callinArr"
                ref="waitTable"
                style="width: 100%;height:100%"
                :highlight-current-row="true"
                cell-class-name="table-cell-custom"
                header-cell-class-name="table-herder-custom"
                size="small"
                empty-text="　"
              >
                <el-table-column prop="realName" show-overflow-tooltip :label="$t('m.NAME')"></el-table-column>
                <el-table-column prop="deviceTel" :label="$t('m.TEL')"></el-table-column>
                <el-table-column prop="groupName" :label="$t('m.PART')"></el-table-column>
                <el-table-column prop="startTimeString" :label="$t('m.WAIT_START_TIME')"></el-table-column>
                <el-table-column prop="talkTime" :label="$t('m.WAIT_TIME')"></el-table-column>
                <el-table-column prop="callStrategy" :label="$t('m.MESSAGE')"></el-table-column>
                <el-table-column align="center" :label="$t('m.DO')">
                  <template slot-scope="scope">
                    <el-dropdown trigger="click">
                      <span class="el-dropdown-link">
                        {{$t('m.ALL_THE_OPERATION')}}
                        <i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item
                          @click.native="handleWaitListDo('accept',scope.row)"
                        >{{$t('m.ANSWER')}}</el-dropdown-item>
                        <el-dropdown-item
                          @click.native="handleWaitListDo('accept',scope.row)"
                        >{{$t('m.REFUSE')}}</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="mid-right-bottom">
              <div class="txt">{{$t('m.KEEP_LIST')}}</div>
              <!-- 保持列表 -->
              <el-table
                :data="keepList"
                ref="keepTable"
                style="width: 100%;height:100%"
                :highlight-current-row="true"
                cell-class-name="table-cell-custom"
                header-cell-class-name="table-herder-custom"
                size="small"
                empty-text="　"
              >
                <el-table-column prop="realName" show-overflow-tooltip :label="$t('m.NAME')"></el-table-column>
                <el-table-column prop="deviceTel" :label="$t('m.TEL')"></el-table-column>
                <el-table-column prop="groupName" :label="$t('m.PART')"></el-table-column>
                <el-table-column prop="startTimeString" :label="$t('m.KEEP_START_TIME')"></el-table-column>
                <el-table-column prop="talkTime" :label="$t('m.KEEP_TIME')"></el-table-column>
                <el-table-column prop="callStrategy" :label="$t('m.MESSAGE')"></el-table-column>
                <el-table-column align="center" :label="$t('m.DO')">
                  <template slot-scope="scope">
                    <el-dropdown trigger="click">
                      <span class="el-dropdown-link">
                        {{$t('m.ALL_THE_OPERATION')}}
                        <i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item
                          @click.native="handleKeepListDo('unHold',scope.row)"
                        >{{$t('m.HOLD_OFF')}}</el-dropdown-item>
                        <el-dropdown-item
                          @click.native="handleKeepListDo('off',scope.row)"
                        >{{$t('m.HANG_UP')}}</el-dropdown-item>
                        <el-dropdown-item
                          @click.native="handleKeepListDo('joinMeet',scope.row)"
                        >{{$t('m.JOIN_THE_MEETING')}}</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div class="address_book">
          <div class="address_book_full">
            <div class="nav">
              <div class="left">
                <div
                  :class="item.isCheck ? 'nameCheck' : 'name'"
                  @click="getChangeTopTitle(item, index)"
                  v-for="(item, index) of topTitleArr"
                  :key="index"
                  v-show="item.isShow"
                >
                  <span>{{ $t('m.dict.titleName')[item.name] }}</span>
                  <div class="arrow"></div>
                </div>
                <div class="center" id="searchButton">
                  <span>{{$t('m.NAMEORTEL')}}:</span>
                  <el-input
                    v-model="input"
                    style="width:50%;margin-left:10px;"
                    clearable
                    :placeholder="$t('m.NAMEORTEL_TIPS')"
                  ></el-input>
                  <img @click="handleSearch" src="../../assets/images/Normal.png" class="left_img" />
                </div>
              </div>

              <div class="right">
                <div class="tel">{{$t('m.OPERATOR_LIST')}}</div>
                <!-- <div class="telNone"></div> -->
              </div>
            </div>
            <div class="content">
              <div class="main">
                <div class="aside" v-show="showTree">
                  <el-scrollbar style="height:100%">
                    <el-tree
                      ref="tree"
                      class="el-tree-class"
                      highlight-current
                      icon-class="el-icon-arrow-right"
                      :data="userGroupTreeData"
                      :default-expanded-keys="expandedTreeKey"
                      @node-click="handleSelectGroup"
                      node-key="id"
                    >
                      <span class slot-scope="{ node, data }">
                        <span>
                          <img
                            style="height:18px"
                            v-if="data.obj.groupType=='dispatchgroup'"
                            src="../../assets/images/DispatchGroup.png"
                          />
                          {{ node.label }}
                        </span>
                      </span>
                    </el-tree>
                  </el-scrollbar>
                </div>
                <!-- 中间区域 -->
                <div
                  :class="selectUserShow || selectTransactionShow? 'main-items set-low-height':'main-items set-high-height'"
                  v-show="showEmployee"
                >
                  <div
                    :class="item.agentState && item.agentState == 'logout'?'main-item logout':'main-item'"
                    v-for="(item, index) of employeeList"
                    :key="'item.defaultNo' + index"
                  >
                    <user-card
                      :item="item"
                      :index="index"
                      :selectTransactionShow="selectTransactionShow"
                      :isBroadbandFlag="false"
                      cardType="normal"
                      :currentTalkObj="currentTalkObj"
                      @handleMakeSelect="handleMakeSelect"
                      @handleAdvanceCall="handleAdvanceCall"
                      @handleMakeCall="handleMakeCall"
                      @handleMakeCallVideo="handleMakeCallVideo"
                      @handleClear="handleClear"
                      @handleHoldCall="handleHoldCall"
                      @handleSingleTransferCall="handleSingleTransferCall"
                      @handleRecordCall="handleRecordCall"
                      @handleForce="handleForce"
                      @handleActivateStun="handleActivateStun"
                      @handleGetItemforTranscation="handleGetItemforTranscation"
                      @handleMeetBack="handleMeetBack"
                      @handleMeetSingleTalk="handleMeetSingleTalk"
                      @handleMeetAllowSpeak="handleMeetAllowSpeak"
                      @handleMeetKick="handleMeetKick"
                      @singleMakeCall="singleMakeCall"
                    ></user-card>
                  </div>
                </div>

                <!--------------------- 嵌入取域-------------------->
                <div v-show="showTopTitleDiv" class="showTopTitleDivClass">
                  <div class="topClass">
                    <!-- <span class="txt">{{titleData.titleStatusName}}</span> -->
                    <el-button
                      v-if="titleData.titleStatus == 'try'"
                      type="danger"
                      class="buttonClass"
                      @click="handleStopByIsCheck()"
                    >{{$t('m.STOP')}}</el-button>
                    <el-button
                      v-if="titleData.titleStatus == 'succ'"
                      type="danger"
                      class="buttonClass"
                      @click="handleCloseByIsCheck()"
                    >{{$t('m.CLOSE')}}</el-button>
                  </div>
                  <div class="main-items-select">
                    <div
                      class="main-item-select"
                      v-for="(item, index) of temDataList"
                      :key="'item.defaultNo' + index"
                    >
                      <user-card
                        :item="item"
                        :index="index"
                        :selectTransactionShow="selectTransactionShow"
                        :isBroadbandFlag="false"
                        cardType="title"
                        @handleMakeSelect="handleMakeSelect"
                        @handleAdvanceCall="handleAdvanceCall"
                        @handleMakeCall="handleMakeCall"
                        @handleMakeCallVideo="handleMakeCallVideo"
                        @handleClear="handleClear"
                        @handleHoldCall="handleHoldCall"
                        @handleSingleTransferCall="handleSingleTransferCall"
                        @handleRecordCall="handleRecordCall"
                        @handleForce="handleForce"
                        @handleActivateStun="handleActivateStun"
                        @handleGetItemforTranscation="handleGetItemforTranscation"
                        @handleMeetBack="handleMeetBack"
                        @handleMeetSingleTalk="handleMeetSingleTalk"
                        @handleMeetAllowSpeak="handleMeetAllowSpeak"
                        @handleMeetKick="handleMeetKick"
                      ></user-card>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 话务员列表 -->
              <div class="main-right" style="overflow: auto;">
                <div v-for="(operator, key) in loginOperatorList" :key="key" style="width:30%">
                  <el-dropdown trigger="click" v-if="operator.status == 'ring'">
                    <div>
                      <img class="img" :src="getOperatorPic(operator)" />
                    </div>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="totalAnswer(operator)">代答</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <div v-else>
                    <img class="img" :src="getOperatorPic(operator)" />
                  </div>
                  <div class="text">{{operator.realName}}</div>
                  <div class="text">{{operator.mainTel}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="my_bottom">
        <webrtc-info></webrtc-info>
      </div>
    </div>
    <!-- 会议 -->
    <Meeting
      v-if="groupCallDialog"
      :groupCallDialog.sync="groupCallDialog"
      :groupOrSelect="groupOrSelect"
      :callingDevice="callingDevice"
      :selectGroupID="selectGroupID"
      :selectUsers="selectUsers"
      :thisSelectMember="thisSelectMember"
      @handleGroupCallBack="handleGroupCallBack"
    />
    <!-- 广播文件上传 -->
    <File
      v-if="fileDialog"
      :broad="FileCalled"
      :flowId="currentBroadChangeToFileFlowId"
      :tel="callingDevice"
      :open.sync="fileDialog"
      :broadcastForm="broadcastForm"
      @handleFileCall="handleFileCall"
    />
    <!-- 广播类型弹出框 -->
    <el-dialog
      custom-class="dialogBackGround"
      :visible.sync="showBroadDialog"
      :close-on-click-modal="false"
      :modal="false"
      width="25%"
    >
      <div slot="title" style="color:white">
        <span>广播类型</span>
        <el-divider></el-divider>
      </div>
      <div style="height:300px">
        <div>
          <el-radio v-model="broadcastForm.callMode" label="manual" class="myRadio">人工广播</el-radio>
          <br />
          <el-radio v-model="broadcastForm.callMode" label="file" class="myRadio">文件广播</el-radio>
          <br />
          <el-radio v-model="broadcastForm.callMode" label="tts" class="myRadio">文字广播</el-radio>
        </div>
        <div
          style="margin-top:30px"
          v-show="broadcastForm.callMode == 'file' ||broadcastForm.callMode == 'tts'"
        >
          <el-radio v-model="broadcastForm.type" label="0" class="myRadio">循环</el-radio>
          <br />
          <el-radio v-model="broadcastForm.type" label="1" class="myRadio">次数</el-radio>
          <el-input
            size="small"
            v-show="broadcastForm.type == 1"
            v-model="broadcastForm.num"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="3"
            style="width:100px"
          ></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleMakeBroadcastType">确定</el-button>
      </span>
    </el-dialog>
    <!-- 职员窗口 -->
    <employee-form
      v-if="openEmployeeForm"
      :title="employeeFormTitle"
      :open.sync="openEmployeeForm"
      :formData="employeeForm"
      @handleUpdateData="handleUpdateData"
    ></employee-form>
    <!-- 操作员窗口 -->
    <operator-form
      v-if="openOperatorForm"
      :title="employeeFormTitle"
      :open.sync="openOperatorForm"
      :formData="employeeForm"
    ></operator-form>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import _ from 'loadsh'
import {
  getEmployee,
  makeCall,
  clearCall,
  getCallrecord,
  getMeetinfo,
  clearConnection,
  getOperatorMember,
} from '@/api/data'
import { getOperator, userStatus } from '@/api/user'
import deepClone from '@/utils/clone'
import Webrtc2Sip from '@/utils/Webrtc2Sip'
import Header from './Header'
import Keyboard from './Keyboard'
import File from './File'
import EmployeeForm from '../Gis/EmployeeForm'
import OperatorForm from '../Gis/OperatorForm'
import UserCard from '../UserCard'
import UserStatus from '../UserCard/UserStatus'
import marqueeX from '../UserCard/marqueeX'
import Meeting from './Meeting'
import store from '@/store'
import { CalculateTime } from '@/utils/util'
import WebrtcInfo from './WebrtcInfo'

export default {
  name: 'Phone',
  components: {
    Keyboard,
    File,
    EmployeeForm,
    OperatorForm,
    UserCard,
    UserStatus,
    marqueeX,
    Meeting,
    Header,
    WebrtcInfo,
  },
  data() {
    return {
      isMain: true,
      input: '',
      employeeList: [],
      temDataList: [],
      MissCall: require('../../assets/images/Missed.png'),
      HangupImg: require('../../assets/images/Hangup.png'),
      //呼入电话静止状态图片
      moreShow: false,
      selectUserShow: false,
      isCall: true,
      selectUsers: [],
      broadID: '',
      rollCallBtnShow: false,
      broadBtnShow: false,
      selectBtnShow: false,
      pollBtnShow: false,
      selectTransactionShow: false,
      record_list: [],
      right_text: '话务员列表',
      groupCallDialog: false,
      meet_list: [],
      selectMeetID: '',
      selectGroupID: '',
      groupOrSelect: '',
      dialDialog: false,
      fileDialog: false,
      textFlag: false,
      textarea: '',
      textareaNum: 0,
      isFileBroad: false,
      telStatus: '',
      isMain: true,
      createMeetForm: {
        meetName: '',
        isAllowSpeak: true,
      },
      userList: [],
      callinArr: [],
      talkArr: [],
      missArr: [],
      dispartArr: [],
      FileCalled: [],
      thisSelectMember: {},
      getTranscationMember: '',
      dialDialogTel: false,
      transcationTel: '',
      showNowStatus: false, //状态弹出框
      transcationTypeFlag: '', //1转移/2转接标志
      showBroadDialog: false,
      topTitleArr: [
        {
          isShow: true,
          isCheck: true,
          name: 'address_book',
          list: [],
        },
        {
          isShow: false,
          isCheck: false,
          name: 'meeting',
          list: [],
        },
        {
          isShow: false,
          isCheck: false,
          name: 'search_result',
          list: [],
        },
      ],
      showTree: true,
      showEmployee: true,
      showTopTitleDiv: false,
      isVideoStatus: false,
      thisSelectCallFlag: false,
      addBroadMemberBtnShow: false,
      thisBroadType: '',
      linkDevice: '', //当前通话对象tel
      thisTopTitleIsBroad: false,
      //标签页数据
      broadSuccArr: [], //广播成员
      selectCallSuccArr: [], //选呼成员
      groupCallSuccArr: [], //组呼成员
      rollSuccArr: [], //点名成员
      pollCallSuccArr: [], //轮询成员
      broadFileName: '', //广播文件名
      thisChooseBroadFlowID: '', //选中的广播标识，加入成员时使用
      currentBroadChangeToFileFlowId: '', //人工广播转文件广播标识
      employeeForm: null, // 职员表单
      openEmployeeForm: false, // 打开职员窗口
      employeeFormTitle: '', // 窗口标题
      openOperatorForm: false,
      expandedTreeKey: [], //默认展开调度组节点key
      groupCallFlag: false,
      titleData: {},
      isClassBig: false, //用户状态class
      isAnswered: false,
      notify: null,
      recordListQuery: {
        calltype: 'singlecall',
        beginIndex: 0,
        count: 20,
      },
      timeBroadcastDialog: false,
      broadcastForm: {
        callMode: 'manual', //manual：人工语音广播,file：自动定时文件广播,tts:  文字广播
        type: '0', //0循环，1次数
        num: '1',
      },
      //摄像头
      camaraBoxPlayingData: [],
      camaraBoxData: [],
      showCamaraBox: false,
      /**
       * 视频分发
       */
      openDistribution: false, // 打开视频分发接口
      distributionSource: {}, // 视频源
      //等待，保持队列
      waitTableData: [],
      keepList: [],
      currentTalkObj: {},
      loginOperatorList: [],
    }
  },
  computed: {
    ...mapState({
      callingDevice(state) {
        return this.isMain
          ? state.cache.operatorInfo.mainTel
          : state.cache.operatorInfo.viceTel
      },
      mainTel: (state) => state.cache.operatorInfo.mainTel,
      viceTel: (state) => state.cache.operatorInfo.viceTel,
      videoMap: (state) => state.cache.videoMap,
      operatorInfo: (state) => state.cache.operatorInfo,
      userGroupTreeData: (state) => state.cache.userGroupTreeData,
      employeeMap: (state) => state.cache.employeeMap,
      operatorMap: (state) => state.cache.operatorMap,
      telOperatorMap: (state) => state.cache.telOperatorMap,
      telEmployeeMap: (state) => state.cache.telEmployeeMap,
      groupMap: (state) => state.cache.groupMap,
      deviceStatusMap: (state) => state.cache.deviceStatusMap,
      localPhoneStatus: (state) => state.cache.localPhoneStatus,
      localButtonStatus: (state) => state.cache.localButtonStatus,
      callFlag: (state) => state.cache.callFlag,
      telMeetingMap: (state) => state.cache.telMeetingMap,
      id2nidMap: (state) => state.cache.id2nidMap,
      deviceLinkMap: (state) => state.cache.deviceLinkMap,
    }),
  },
  watch: {
    userGroupTreeData() {
      this.fiterUserGroupTreeData()
    },
  },
  methods: {
    init() {
      //初始化在线操作员
      let _this = this
      setTimeout(function () {
        for (let operator of _this.operatorMap.values()) {
          if (
            operator.agentState == 'login' &&
            operator.mainTel != _this.mainTel
          ) {
            _this.loginOperatorList.push(operator)
          }
        }
      }, 1000)
    },
    // 对数据进行过滤
    fiterUserGroupTreeData() {
      const convert = (arr) => {
        const newArr = arr.filter(
          (item) =>
            item.obj.groupType !== 'clustergroup' &&
            item.obj.groupType !== 'dynamicgroup'
        )
        return newArr.map((item) => {
          if (item.children) {
            item.children = convert(item.children)
          }
          return item
        })
      }
      return convert(this.userGroupTreeData)
    },
    //自定义摘机信号事件
    handleLocalPhoneAccept(msg) {
      const deviceStatus = this.deviceStatusMap.get(this.callingDevice)
      console.log('phone模块-<软电话状态>', deviceStatus)
      if (
        deviceStatus != 'idle' &&
        deviceStatus != 'offline' &&
        deviceStatus != undefined
      ) {
        console.log('phone模块-<应答状态>', this.isAnswered)
        if (this.isAnswered) {
          //挂断,话机放下并且扬声器按钮关闭状态
          if (
            this.localPhoneStatus == 'off' &&
            this.localButtonStatus == 'jyoff'
          ) {
            window.handlePlayDialt('pause')
            let webrtc2Sip = Webrtc2Sip.getWebrtc2SipByName(this.callingDevice)
            console.log('挂断')
            this.handleReject(webrtc2Sip)
          }
        } else {
          //话机拿起或按扬声器按钮->接听
          if (msg == 'on' || msg == 'jyon') {
            window.handlePlayDialt('pause')
            let webrtc2Sip = Webrtc2Sip.getWebrtc2SipByName(this.callingDevice)
            this.handleAccept(webrtc2Sip)
            //关闭来电显示
            if (this.notify) this.notify.close()
          }
        }
      } else {
        if (this.localPhoneStatus == 'on') {
          window.handlePlayDialt('play')
        }
        if (
          this.localPhoneStatus == 'off' &&
          this.localButtonStatus == 'jyoff'
        ) {
          window.handlePlayDialt('pause')
        }
      }
    },
    /**
     * 设置自定义事件
     */
    setWebrtcCostumEvent() {
      let webrtc2Sip = Webrtc2Sip.getWebrtc2SipByName(this.callingDevice)
      if (webrtc2Sip) {
        webrtc2Sip.setCustomEvent(this.sessionEvent, this.stackEvent)
        // webrtc2Sip.playVideo()
        webrtc2Sip.setVideoDom('remoteVideo', 'videoLocal')
        // console.log('设置自定义事件成功===' + this.callingDevice)
      }
    },
    // sip栈事件 -- 来电等事件
    stackEvent(e, webrtc2Sip) {
      let _this = this
      console.log('调用局部页面事件 Phone stackEvent', e.type, e.description)
      if (e.type === 'i_new_call') {
        console.log('拨打电话状态=====' + _this.callFlag)
        if (_this.callFlag) {
          webrtc2Sip.sipAnswer()
          this.isAnswered = true
          store.commit('callFlagEvent', false)
        } else {
          _this.incomingNotify(e.incomingName, webrtc2Sip)
        }
      }
    },
    // 会话事件 -- 挂断等
    sessionEvent(e, sessionType, webrtc2Sip) {
      console.log('Phone sessionEvent', e.type, e.description)
      if (e.type === 'terminating' || e.type === 'terminated') {
        this.closeNotify()
        // console.log('关来电提醒')
        //清除Webrtc2Sip自定义事件
        //webrtc2Sip.clearCustomEvent();
      }
    },
    // 拒接或挂断
    handleReject(webrtc2Sip) {
      let _this = this
      console.log('handleReject')
      window.handlePlayDialt('pause')
      if (webrtc2Sip) {
        if (this.isAnswered) {
          webrtc2Sip.sipHangUp()
        } else {
          webrtc2Sip.sipHangUp()
          //拆线
          if (this.callinArr.length > 0) {
            let tel = this.callinArr[0].deviceTel
            this.handleClearConnection(tel)
          }
        }
      }
      this.closeNotify()
    },
    // 接听
    handleAccept(webrtc2Sip) {
      let _this = this
      this.isAnswered = true
      window.handlePlayDialt('pause')
      store.commit('callFlagEvent', false)
      console.log('handleAnswer')
      if (webrtc2Sip) webrtc2Sip.sipAnswer()
      let answerEl = document.getElementById('answer')
      if (answerEl) answerEl.style.display = 'none'
    },
    // 关闭来电显示
    closeNotify() {
      if (this.notify) this.notify.close()
      this.isAnswered = false
    },
    // 来电显示
    incomingNotify(incomingName = '未知', webrtc2Sip) {
      const h = this.$createElement
      this.closeNotify()
      this.notify = this.$notify({
        position: 'bottom-right',
        duration: 0,
        showClose: false,
        customClass: 'ring-pop-up',
        dangerouslyUseHTMLString: true,
        message: h('div', { attrs: { class: 'ring-pop-up-content' } }, [
          h('div', { attrs: { class: '__title' } }, `   有新的来电   `),
          h('div', { attrs: { class: '__button' } }, [
            h(
              'svg-icon',
              {
                attrs: {
                  'icon-class': 'answer',
                  id: 'answer',
                },
                on: {
                  click: () => this.handleAccept(webrtc2Sip),
                },
              },
              null
            ),
            h(
              'svg-icon',
              {
                attrs: {
                  'icon-class': 'hangup',
                  id: 'hangup',
                },
                on: {
                  click: () => this.handleReject(webrtc2Sip),
                },
              },
              null
            ),
          ]),
        ]),
      })
    },
    //上报事件
    event(e) {
      let _this = this
      console.log(e)
      switch (e.type) {
        case 'BroadcastCall':
          if (e.mesg_id == 'TimingBroadcast') {
            //不处理定时广播上报的数据
            return
          }
          this.broadID = e.eventdata.flowID
          this.selectUserShow = false
          //广播
          if (e.result == 'succ') {
            if (this.isFileBroad) {
              this.textFlag = false
              this.fileDialog = false
              this.dialogBackGround = false
            }
            //广播发起完成，更改状态
            this.handleGetCurremtTitleIndex(e.eventdata.flowID)
          } else if (e.result == 'fail') {
            this.showEmployee = false
            if (e.reason == '336:flet is killed') {
              //点击关闭广播触发，更新成员状态为失败
              this.topTitleArr.forEach((el) => {
                if (el.flowID == e.eventdata.flowID) {
                  el.list.forEach((element) => {
                    if (element.deviceStatus != 'broadcast') {
                      element.callStatusName = '失败'
                      element.realName = element.realName + ' '
                    }
                  })
                  this.temDataList = el.list
                }
              })
              return
            }
            this.$message.warning('广播发起失败')
            return
          } else {
            let arr = this.topTitleArr.filter((el) => {
              return el.flowID == e.eventdata.flowID
            })
            if (arr.length == 0) {
              this.topTitleArr.forEach((e) => {
                e.isCheck = false
              })
              this.titleData = {
                isCheck: true,
                name: '广播',
                flowID: e.eventdata.flowID,
                list: this.broadSuccArr,
                titleStatus: 'try',
                fileName: this.broadFileName,
              }
              this.topTitleArr.push(this.titleData)
              this.thisTopTitleIsBroad = true
            }
            //更新广播呼叫失败状态
            this.updateMemberFailStatus(e)
            let arrg = this.topTitleArr.filter((el) => {
              return el.flowID == e.eventdata.flowID
            })
            this.temDataList = arrg[0].list
          }
          break
        case 'UserStatus':
          //用户状态
          if (e.deviceTel == this.callingDevice) {
            this.telStatus = e.deviceStatus
          }
          //维护userList
          for (let i = 0; i < this.userList.length; i++) {
            if (this.userList[i].deviceTel == e.deviceTel) {
              this.userList[i].deviceStatus = e.deviceStatus
              break
            }
            if (i == this.userList.length - 1) {
              this.userList.push({
                deviceTel: e.deviceTel,
                deviceStatus: e.deviceStatus,
              })
            }
          }
          //维护employeeList
          for (let index = 0; index < this.employeeList.length; index++) {
            let element = this.employeeList[index]
            if (e.deviceTel == element.defaultNo) {
              element.deviceStatus = e.deviceStatus
              this.$set(this.employeeList, index, element)
              break
            }
          }
          //维护temDataList
          for (let index = 0; index < this.temDataList.length; index++) {
            let element = this.temDataList[index]
            if (e.deviceTel == element.defaultNo) {
              element.deviceStatus = e.deviceStatus
              this.$set(this.temDataList, index, element)
              break
            }
          }
          //维护talkArr
          for (let j = 0; j < this.talkArr.length; j++) {
            let ele = this.talkArr[j]
            if (e.deviceTel == ele.defaultNo) {
              ele.deviceStatus = e.deviceStatus
              if (e.deviceStatus == 'ring') {
                this.telStatus = 'callin'
              }
              this.$set(this.talkArr, j, ele)
              break
            }
          }
          if (e.deviceTel == this.callingDevice && e.linkDevice != null) {
            const obj = this.makeCurrentTalkObj(e.linkDevice)
            this.currentTalkObj = obj
          }
          if (e.deviceStatus == 'talk' && e.deviceTel == this.callingDevice) {
            //获取当前通话对象
            this.linkDevice = e.linkDevice
            sessionStorage.setItem('linkDevice', e.linkDevice)
          }
          if (e.deviceStatus == 'idle' && e.deviceTel == this.callingDevice) {
            this.linkDevice = ''
            sessionStorage.setItem('linkDevice', '')
            //如果在组织栏目就关闭视频窗口
            if (this.topTitleArr[0].isCheck) {
              this.isVideoStatus = false
              this.showNowStatus = false
              this.showEmployee = true
              if (document.getElementById('statusDiv')) {
                document.getElementById('statusDiv').style = 'display:flex;'
              }
            }
            //关闭来电显示
            this.closeNotify()
            //关闭联动视频
            this.showCamaraBox = false
            this.camaraBoxData = []
            sessionStorage.removeItem('phone_linked_video_play_data')
            //清空当前通话
            this.currentTalkObj = {}
          }
          //视频通话//视频呼叫
          if (
            e.deviceStatus == 'talk' &&
            e.isVideo == true &&
            e.deviceTel == this.callingDevice
          ) {
            this.handleOpenWebrtcVideo()
          }
          //从呼入电话中移除
          if (e.deviceStatus == 'talk') {
            this.callinArr = this.callinArr.filter((deviceTel) => {
              return deviceTel.deviceTel != e.deviceTel
            })
          }
          if (e.deviceStatus == 'idle') {
            //职员退出正在通话,退出等待列表,退出保持列表
            this.handleExitTalkArr(e.deviceTel)
          }
          if (
            e.deviceStatus == 'talk' &&
            e.deviceTel == this.callingDevice &&
            e.linkDevice != this.callingDevice
          ) {
            //职员加入正在通话
            this.handleJoinTalkArr(e.linkDevice)
            //退出保持列表
            this.handleExitKeepList(e.linkDevice)
          }
          if (e.deviceStatus == 'hold') {
            if (e.deviceTel == this.callingDevice) {
              //操作员为呼叫保持状态，清空正在通话
              this.talkArr = []
            } else {
              //加入保持列表
              this.handleAddKeepList(e.deviceTel)
            }
          }
          if (
            (e.deviceStatus == 'allowspeak' || e.deviceStatus == 'banspeak') &&
            e.deviceTel == this.callingDevice
          ) {
            //会议中，职员加入正在通话
            this.handleJoinTalkArr(e.deviceTel)
          }
          //话机拨打调度台事件处理
          if (e.direct == 'callin') {
            if (e.deviceTel == this.callingDevice) {
              if (e.deviceStatus == 'talk' && e.linkDevice) {
                this.callinArr = this.callinArr.filter((deviceTel) => {
                  return deviceTel.deviceTel != e.linkDevice
                })
              }
              if (e.deviceStatus == 'idle') {
                this.talkArr = this.talkArr.filter((deviceTel) => {
                  return deviceTel.defaultNo != e.deviceTel
                })
              }
              if (e.deviceStatus == 'ring') {
                //operatorID 相同为拨打给本调度员
                let operatorid = sessionStorage.getItem('operatorid')
                if (e.operatorID == operatorid) {
                  //加入呼入电话
                  this.handleCallin(e.linkDevice)
                }
              }
            } else {
              if (e.deviceStatus == 'idle') {
                //处理用户拨打挂断，上报信息不全面，单独处理
                this.handleMissArr(e)
              } else if (
                e.deviceStatus == 'ring' ||
                e.deviceStatus == 'queue'
              ) {
                let operatorid = sessionStorage.getItem('operatorid')
                if (e.operatorID == operatorid) {
                  //加入呼入电话
                  this.handleCallin(e.linkDevice)
                }
                if (e.operatorID == null) {
                  //加入呼入电话
                  this.handleCallin(e.deviceTel)
                }
              }
            }
          } else if (e.direct == 'null') {
            //内呼  通话中
            if (e.deviceTel == this.callingDevice) {
              if (e.deviceStatus == 'monitorring') {
              } else if (e.deviceStatus == 'idle') {
                //关闭来电显示
                this.closeNotify()
                //清空正在呼入
                // this.callinArr = []
                //判断是否加入未接来电
                let queueUser = this.userList.filter((user) => {
                  return user.deviceStatus == 'queue'
                })
                if (queueUser.length > 0) {
                  let emp = this.telEmployeeMap.get(queueUser[0].deviceTel)
                  if (emp) {
                    let empData = {
                      deviceTel: queueUser[0].deviceTel,
                      realName: emp.realName,
                      groupName: emp.groupName,
                    }
                    this.handleJoinMissCall(empData)
                  } else {
                    let empData = {
                      deviceTel: queueUser[0].deviceTel,
                    }
                    this.handleJoinMissCall(empData)
                  }
                }
              }
            } else {
              //处理用户拨打挂断，上报信息不全面，单独处理
              if (e.deviceStatus == 'idle') {
                this.handleMissArr(e)
              }
            }
          } else if (
            //调度台呼出
            e.direct == 'callout' &&
            e.deviceTel == this.callingDevice
          ) {
            //调度台呼叫他人
            if (e.deviceStatus == 'talk') {
              this.callinArr = this.callinArr.filter(
                (deviceTel) => deviceTel == e.deviceTel
              )
            } else if (e.deviceStatus == 'idle') {
              //职员退出正在通话
              this.handleExitTalkArr(e.linkDevice)
            } else if (e.deviceStatus == 'ring') {
              //如果operatorID不和自己operatorID相同，判断是外面打进来
              let operatorid = sessionStorage.getItem('operatorid')
              if (e.operatorID != operatorid) {
                // this.callinFlag = true
                // console.log('调度台电话呼入=====' + this.callinFlag)
              }
            }
          }
          break
        case 'EndBroadcastCall':
          if (e.result == 'fail') {
            if (e.reason != '300:cannot get session by id') {
              this.$message.warning('广播关闭失败')
              return
            }
          }
          this.selectUserShow = false
          this.isCall = true
          this.broadBtnShow = false
          break
        case 'GroupCall':
          //组呼
          if (!this.groupCallFlag) {
            return
          }
          if (e.result == 'fail') {
            if (e.reason == '336:flet is killed') {
              return
            }
            if (e.reason == '361:operator handle not accept') {
              this.$message({
                message: `组呼失败:操作员手柄无应答`,
                type: 'error',
              })
              return
            }
            this.$message({
              message: `组呼失败`,
              type: 'error',
            })
            return
          } else if (e.result == 'succ') {
            //发起完成，更改状态
            this.handleGetCurremtTitleIndex(e.eventdata.flowID)
          }
          let arrT = this.topTitleArr.filter((el) => {
            return el.flowID == e.eventdata.flowID
          })
          if (arrT.length == 0) {
            this.topTitleArr.forEach((e) => {
              e.isCheck = false
            })
            this.titleData = {
              isCheck: true,
              name: '组呼',
              flowID: e.eventdata.flowID,
              meetID: e.eventdata.meetID,
              titleStatus: 'try',
              list: this.groupCallSuccArr,
            }
            this.topTitleArr.push(this.titleData)
          }
          //更新组呼成员失败状态
          this.updateMemberFailStatus(e)
          this.temDataList = this.groupCallSuccArr
          this.selectUserShow = false
          break
        case 'EndGroupCall':
          break
        case 'SelectCall':
          if (e.result == 'fail') {
            if (e.reason == '318:join meet error') {
              this.$message.warning(
                this.$i18n.locale == 'en-US'
                  ? 'join meet error'
                  : '加入会议失败'
              )
              return
            }
            this.$message.warning(
              this.$i18n.locale == 'en-US' ? e.reson : '选呼失败'
            )
            return
          }
          if (this.thisSelectCallFlag) {
            //选呼
            if (e.result == 'succ') {
              this.thisSelectCallFlag = false
              //选呼完成，更改状态
              this.handleGetCurremtTitleIndex(e.eventdata.flowID)
            }
            let arr = this.topTitleArr.filter((el) => {
              return el.flowID == e.eventdata.flowID
            })
            if (arr.length == 0) {
              this.topTitleArr.forEach((e) => {
                e.isCheck = false
              })
              this.titleData = {
                isCheck: true,
                name: '选呼',
                flowID: e.eventdata.flowID,
                meetID: e.eventdata.meetID,
                titleStatus: 'try',
                list: this.selectCallSuccArr,
              }
              this.topTitleArr.push(this.titleData)
            }
            //更新选呼成员失败状态
            this.updateMemberFailStatus(e)
            this.temDataList = this.selectCallSuccArr
            this.selectUserShow = false
          }
          break
        case 'EndSelectCall':
          break
        case 'CreateMeet':
          if (e.result == 'succ') {
            this.$message({
              message: '创建成功',
              type: 'success',
            })
            getMeetinfo().then((res) => {
              this.meet_list = res.data.meet_list.filter(
                (e) => e.meetMode == 'audio'
              )
              // console.log(this.meet_list.length)
              this.createMeetForm.meetName = ''
              this.createMeetForm.isAllowSpeak = true
            })
          }
          break
        case 'ClearConnection':
          if (e.result == 'succ') {
            this.callinArr = this.callinArr.filter(
              (deviceTel) => deviceTel == this.currentClear
            )
          }
          break
        case 'HoldCall' || 'UnHoldCall':
          //呼叫保持,解除保持
          for (let index = 0; index < this.employeeList.length; index++) {
            const element = this.employeeList[index]
            if (e.deviceTel == element.defaultNo) {
              element.deviceStatus = e.deviceStatus
              this.$set(this.employeeList, index, element)
              break
            }
          }
          break
        case 'TransferCall':
          //呼叫转接"TransferCall"
          if (e.result == 'fail') {
            this.$message({
              message: `呼叫转接失败${e.reason}`,
              type: 'error',
            })
            return
          } else if (e.result == 'succ') {
            //将自己拆线
            this.handleClearConnection(this.callingDevice)
          }
          break
        case 'MonitorCall':
          //监听
          if (e.result == 'fail') {
            this.$message({
              message: `监听失败${e.reason}`,
              type: 'error',
            })
            return
          }
          break
        case 'ForceInsertCall':
          //强插
          if (e.result == 'fail') {
            this.$message({
              message: `强插失败${e.reason}`,
              type: 'error',
            })
            return
          }
          break
        case 'ForceReleaseCall':
          //强拆
          if (e.result == 'fail') {
            this.$message({
              message: `强拆失败${e.reason}`,
              type: 'error',
            })
            return
          }
          break
        case 'ForceClearCall':
          //强断
          if (e.result == 'fail') {
            this.$message({
              message: `强断失败${e.reason}`,
              type: 'error',
            })
            return
          }
          break
        case 'MakeCall':
          if (e.result == 'fail') {
            if (this.$i18n.locale == 'en-US') {
              this.$message.warning(e.reason)
              return
            } else {
              if (e.reason == '356:operator handle clear connection') {
                //操作员中断电话
                this.$message.warning('操作手柄断开连接')
                return
              } else if (e.reason == '362:operator user unavail') {
                this.$message.warning('拨打关闭')
                return
              } else if (e.reason == '336:flet is killed') {
                //进程被杀
                return
              } else if (e.reason == '349:called user clear connection') {
                this.$message.warning('被调用用户清除连接')
                return
              } else if (e.reason == '322:caller user is same to called user') {
                this.$message.warning('主被叫相同')
                return
              } else if (e.reason == '361:operator handle not accept') {
                this.$message.warning('操作手柄拒接')
                return
              } else if (e.reason == '355:called user unavail') {
                this.$message.warning('用户拒接')
                return
              } else if (e.reason == '353:called user time out no answer') {
                this.$message.warning('用户超时未接听')
                return
              } else if (
                e.reason == '308:user status is error, not allow call'
              ) {
                this.$message.warning('用户处于不可呼叫状态')
                return
              } else if (e.reason == '353:called user time out no answer') {
                this.$message.warning('用户无应答')
                return
              } else if (e.reason == '351:called user busy') {
                this.$message.warning('用户忙')
                return
              } else if (e.reason == '358:operator handle busy') {
                this.$message.warning('手柄已挂机')
                return
              }
              this.$message.warning('拨打失败：' + e.reason)
              return
            }
          }
          break
        case 'meet_member_event':
          //踢出会议
          if (e.event == 'DelMeetMember') {
            let ter = this.topTitleArr.filter((e) => {
              return e.isCheck == true
            })
            if (ter.name == '选呼') {
              this.temDataList = this.selectCallSuccArr.filter((item) => {
                return e.user != item.defaultNo
              })
            } else if (ter.name == '组呼') {
              this.groupCallSuccArr = this.groupCallSuccArr.filter((item) => {
                return e.user != item.defaultNo
              })
            }
          } else if (e.event == 'NewMeetMember') {
            if (e.user != this.mainTel) {
              //视频会议，发起混码
              if (this.isVideoStatus) {
                let mixSources = [
                  {
                    calledDevice: this.callingDevice,
                  },
                  {
                    calledDevice: e.user,
                  },
                ]
                let form = {
                  meetID: e.meetID,
                  mixType: 2,
                  videoType: '720P',
                  sources: mixSources,
                }
                SDK.setMeetVideoMix(form)
              }
            }
            this.isVideoStatus = true
          }
          break
        case 'AdvanceCall':
          if (e.result == 'fail') {
            if (e.reason == '336:flet is killed') {
              return
            }
            this.$message.warning(
              this.$i18n.locale == 'en-US' ? e.reason : '强呼失败：' + e.reason
            )
            return
          }
          break
        case 'EmployeeMod':
          if (e.result == 'succ') {
            //更新修改职员数据
            console.log('职员修改成功')
            this.handleUpdateData()
          } else if (e.result == 'fail') {
            console.log('修改失败')
            this.$message.warning(
              this.$i18n.locale == 'en-US' ? e.reason : '修改失败'
            )
          }
          break
        case 'OperatorMod':
          if (e.result == 'succ') {
            //更新修改职员数据
            console.log('职员修改成功')
            this.handleUpdateData()
          } else if (e.result == 'fail') {
            console.log('修改失败')
            this.$message.warning(
              this.$i18n.locale == 'en-US' ? e.reason : '修改失败'
            )
          }
          break
        case 'AnswerCall':
          //应答成功，软电话自动接听
          if (e.result == 'succ') {
            //软电话接听
            let webrtc2Sip = Webrtc2Sip.getWebrtc2SipByName(this.callingDevice)
            if (webrtc2Sip) {
              this.handleAccept(webrtc2Sip)
            }
          }
          break
        case 'GroupAnswerCall':
          if (e.result == 'succ') {
            //清空呼入电话,来电显示关闭
            this.callinArr = []
            this.notify.close()
          } else if (e.result == 'fail') {
            if (e.reason == '318:join meet error') {
              this.$message.warning(
                this.$i18n.locale == 'en-US' ? e.reason : '加入会议失败'
              )
              return
            }
            this.$message.warning(
              this.$i18n.locale == 'en-US' ? e.reason : '群答失败'
            )
          }
          break
        case 'MeetStatusEvent':
          if (e.event != 'ModMeet') {
            return
          }
          if (e.meetMode == 'video') {
          }
        case 'ConsultCall':
          if (e.result == 'succ') {
            let heldDevice = e.mesg_id
            //发起转接
            let form = {
              heldDevice: heldDevice,
              activeDevice: this.currentTalkObj.deviceTel,
            }
            this.currentTalkObj.consultForm = form
            // SDK.transferCall(form)
          } else if (e.result == 'fail') {
            return this.$message({
              message: `转接失败，呼叫转接用户忙`,
              type: 'error',
            })
          }
          break
        case 'SingleTransferCall':
          if (e.result == 'succ') {
            //将自己拆线
            this.handleClearConnection(this.callingDevice)
          }
          break
        case 'AgentStatusEvent':
          if (e.agentID == this.operatorInfo.operatorID) {
            this.operatorInfo.agentState = e.agentState
          } else {
            if (e.agentState == 'login') {
              let operator = this.operatorMap.get(e.agentID)
              this.loginOperatorList.push(operator)
            } else {
              let flag = this.loginOperatorList.some((user) => {
                return user.operatorID == e.agentID
              })
              if (flag) {
                this.loginOperatorList = this.loginOperatorList.filter(
                  (user) => {
                    return user.operatorID != e.agentID
                  }
                )
              }
            }
          }

          break
        default:
          break
      }
    },
    //组织树节点点击事件
    handleSelectGroup(node) {
      let _this = this
      this.selectGroupID = node.id
      const groupType = node.obj.groupType
      if (groupType === 'dispatchgroup') {
        getOperatorMember({ groupid: node.id }).then((re) => {
          let arry = re.data.data.operator.map((e) => ({
            type: 'operator',
            defaultNo: e.mainTel,
            realName: e.realName,
            order: e.orderNO,
            telType: e.mainTelType == 'phone' ? '话机' : '手咪',
            myDutyName: '调度员',
            group: [{ groupID: e.groupID, orderNO: e.orderNO }],
            device: [
              {
                deviceTel: e.mainTel,
                deviceType: e.mainTelType,
                isCheck: true,
              },
              {
                deviceTel: e.viceTel,
                deviceType: e.viceTelType,
                isCheck: false,
              },
            ],
            agentState: e.agentState, //登录状态 logout/login
            obj: deepClone(e),
          }))
          this.dealUserData(arry, node)
        })
      } else {
        getEmployee({ groupid: node.id }).then((res) => {
          let arr = res.data.data.employee
          arr.forEach((e) => {
            e.obj = deepClone(e)
            e.myDutyName = e.dutyName.length > 0 ? e.dutyName[0] : '无职务'
            e.type = 'employee'
            e.device.forEach((el, index) => {
              el.isCheck = false
              if (e.defaultNo == el.deviceTel) {
                el.isCheck = true
              }
            })
          })
          this.dealUserData(arr, node)
        })
      }
    },
    //处理某组织下用户数据
    dealUserData(arr, node) {
      for (let index = 0; index < arr.length; index++) {
        const el = arr[index]
        el.deviceStatus = 'idle' //默认空闲
        el.isRecord = true //默认开启录音
        const status = this.deviceStatusMap.get(el.defaultNo)
        if (status) {
          el.deviceStatus = status
        } else {
          el.deviceStatus = 'idle'
        }
        let filterArr = el.group.filter((groupItem) => {
          return groupItem.groupID == node.id
        })
        if (filterArr.length > 0) {
          el.orderNO = filterArr[0].orderNO
        }
      }
      //根據距order排序
      arr.sort(function (a, b) {
        return a.orderNO - b.orderNO
      })
      this.employeeList = arr
    },
    //用户手机号类型转换
    getTelType(type) {
      let typeName = ''
      if (type == 'office' || type == 'Office') {
        typeName = '办公号码'
      } else if (type == 'Home') {
        typeName = '家庭号码'
      } else if (type == 'Mobile') {
        typeName = '移动号码'
      } else if (type == 'Fax') {
        typeName = '传真号码'
      } else if (type == 'Linkage') {
        typeName = '联动号码'
      } else if (type == 'Wireless' || type == 'wireless') {
        typeName = '无线终端'
      } else if (type == 'pocgroup') {
        typeName = 'POC群组'
      } else if (type == 'poc') {
        typeName = 'POC终端'
      } else if (type == 'soldier') {
        typeName = '单兵终端'
      } else if (type == 'Video') {
        typeName = '视频终端'
      } else if (type == 'phone') {
        typeName = '话机'
      } else if (type == 'hand_microphone') {
        typeName = '手咪'
      } else {
        typeName = '手咪'
      }
      return typeName
    },
    //语音呼叫（点击员工div事件）
    handleMakeCall(calledDevice, name, item, index) {
      if (this.selectTransactionShow && this.transcationTypeFlag == '转接') {
        //呼叫转接-》发起咨询呼叫-》转接
        this.consultCall(calledDevice)
        this.getTranscationMember = item
      } else if (
        this.selectTransactionShow &&
        this.transcationTypeFlag == '转移'
      ) {
        this.getTranscationMember = item
      } else if (this.selectUserShow) {
        //选中用户框打开状态
        item.calledDevice = item.defaultNo
        item.callStatusName = ''
        this.selectUsers.push(deepClone(item))
        this.selectUsers = _.uniqBy(this.selectUsers, 'calledDevice')
      } else {
        if (item.deviceStatus == 'talk' || item.deviceStatus == 'monitortalk') {
          this.$message.warning(
            this.$i18n.locale == 'en-US' ? 'user is talking' : '对方正在通话中'
          )
          return
        }
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'MakeCall',
            callingDevice: this.callingDevice,
            called: { calledDevice },
            callType: 'audio',
            duplexMode: 'full',
          },
        }).then((res) => {
          store.commit('callFlagEvent', true) // vuex缓存
          window.handlePlayDialt('pause')
        })
      }
    },
    //简单呼叫
    singleMakeCall(calledDevice) {
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'MakeCall',
          callingDevice: this.callingDevice,
          called: { calledDevice },
          callType: 'audio',
          duplexMode: 'full',
        },
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //咨询呼叫
    consultCall(calledDevice) {
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'ConsultCall',
          callingDevice: this.callingDevice,
          activeDevice: this.thisSelectMember.defaultNo,
          called: { calledDevice: calledDevice, userID: null },
          callType: 'audio',
        },
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //挂断
    handleClearCall() {
      clearCall({})
      store.commit('callFlagEvent', false) // vuex缓存
      this.currentTalkObj = {}
    },
    //拆线
    handleClearConnection(calledDevice) {
      clearConnection({
        request: {
          '@id': '100000',
          '@type': 'ClearConnection',
          calledDevice: calledDevice,
          userID: null,
        },
      })
      this.currentTalkObj = {}
    },
    //切换通话记录
    handleRecord(txt) {
      this.moreShow = false
      switch (txt) {
        case '通话记录':
          this.right_text = txt
          this.recordListQuery.beginIndex = 0
          getCallrecord(this.recordListQuery).then((res) => {
            const { record_list } = res.data
            this.record_list = record_list
          })
          break
        case '呼入电话':
          this.right_text = txt
          break
        case '正在通话':
          this.right_text = txt
          break
        case '未接来电':
          this.right_text = txt
          break
        case '分发管理':
          this.right_text = txt
          this.dispartArr =
            sessionStorage.getItem('partVideoList') == null
              ? []
              : JSON.parse(sessionStorage.getItem('partVideoList'))
          break
        default:
          break
      }
    },
    //发起广播
    handleBroadcast() {
      this.moreShow = false
      this.selectUserShow = true
      this.isCall = false
      this.broadBtnShow = true
      this.rollCallBtnShow = false
      this.selectBtnShow = false
      this.pollBtnShow = false
      this.broadSuccArr = []
      this.currentBroadChangeToFileFlowId = ''
      // this.handleChangeToFirstTitle()
    },
    //删除选中用户
    handleTagClose(calledDevice) {
      this.selectUsers = this.selectUsers.filter(
        (e) => e.calledDevice != calledDevice
      )
    },
    //打开人工广播
    handleBroadManual() {
      this.thisBroadType = 'manual'
      this.showBroadDialog = false
      this.broadSuccArr = this.selectUsers
      const called = this.selectUsers.map((e) => ({
        calledDevice: e.calledDevice,
        userID: null,
      }))
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'BroadcastCall',
          callingDevice: this.callingDevice,
          called,
          callMode: 'manual',
          time: null,
          callLoop: 0,
          flowID: null,
        },
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //关闭广播
    handleEndBroadcastCall() {
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'EndBroadcastCall',
          flowID: this.broadID,
        },
      })
      store.commit('callFlagEvent', false) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //打开点名clos
    handleRollCall() {
      this.moreShow = false
      this.selectUserShow = true
      this.isCall = false
      this.rollCallBtnShow = true
      this.broadBtnShow = false
      this.selectBtnShow = false
      this.pollBtnShow = false
      this.rollSuccArr = []
      this.selectUsers = []
    },
    //打开选呼
    handleSelectCall() {
      this.groupOrSelect = 'select'
      this.moreShow = false
      this.selectUserShow = true
      this.isCall = false
      this.broadBtnShow = false
      this.pollBtnShow = false
      this.selectBtnShow = true
    },
    //开始 点名
    handleRoll() {
      const called = this.selectUsers.map((e) => ({
        calledDevice: e.calledDevice,
        userID: null,
      }))
      if (called.length == 0) {
        this.$message.warning('点名成员不能为空')
      }
      this.rollSuccArr = this.selectUsers
      this.rollSuccArr.forEach((e) => {
        e.callStatusName = ''
      })
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'RollCall',
          callingDevice: this.callingDevice,
          callMode: 'parallel',
          called,
        },
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //打开轮询
    handlePollCall() {
      this.moreShow = false
      this.selectUserShow = true
      this.isCall = false
      this.pollBtnShow = true
      this.broadBtnShow = false
      this.selectBtnShow = false
    },
    //开始轮询
    handleCallPoll() {
      this.pollCallSuccArr = this.selectUsers
      const called = this.selectUsers.map((e) => ({
        calledDevice: e.calledDevice,
        userID: null,
      }))
      this.pollCallSuccArr.forEach((e) => {
        e.callStatusName = ''
      })
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'PollCall',
          callingDevice: this.callingDevice,
          called,
          callType: 'audio',
        },
      }).then((res) => {
        if (res.data.msg == 'try') {
        }
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //打开会议 组件
    handleMakeSelect(type, item) {
      this.handleOpenMeeting(item.defaultNo)
    },
    //打开会议列表
    handleGroupCall() {
      let _this = this
      if (this.selectGroupID == '') {
        this.$message.warning('请先选中一个组')
        return
      }
      this.groupOrSelect = 'group'
      this.groupCallDialog = true
      this.moreShow = false
      this.isCall = false
      this.selectMeetID = ''
    },
    //会议窗口组件-回调
    handleGroupCallBack(type) {
      this.groupCallFlag = true
      store.commit('callFlagEvent', true)
      window.handlePlayDialt('pause')
      if (type == 'groupCall') {
        this.groupCallSuccArr = this.employeeList
      } else if (type == 'selectCall') {
        this.selectCallSuccArr = this.selectUsers
      } else if (type == 'GroupAnswerCall') {
      } else {
      }
    },
    //闭铃
    handleSuspendRing() {
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'SuspendRing',
        },
      })
    },
    //打开文件广播
    handleFileBroad() {
      this.thisBroadType = 'file'
      this.showBroadDialog = false
      this.broadSuccArr = this.selectUsers
      const called = this.selectUsers.map((e) => ({
        calledDevice: e.calledDevice,
        userID: null,
      }))
      this.FileCalled = called
      this.fileDialog = true
    },
    //切换到文件广播
    changeFileBroad() {
      const called = this.temDataList.map((e) => ({
        calledDevice: e.calledDevice,
        userID: null,
      }))
      this.FileCalled = called
      //标注是切换广播状态
      this.topTitleArr.forEach((e) => {
        if (e.isCheck) this.currentBroadChangeToFileFlowId = e.flowID
      })
      this.fileDialog = true
      this.thisBroadType = 'file'
    },
    //打开文字广播
    handleTextBroad() {
      this.thisBroadType = 'tts'
      this.showBroadDialog = false
      this.textFlag = true
      this.textarea = ''
      if (this.$refs.uploads) this.$refs.uploads.value = ''
    },
    //切换主副手柄
    handleToggleTel(isMain) {
      let _this = this
      this.isMain = isMain
      let arr = []
      if (this.isMain) {
        arr = this.userList.filter((e) => {
          return e.deviceTel == _this.mainTel
        })
      } else {
        arr = this.userList.filter((e) => {
          return e.deviceTel == _this.viceTel
        })
      }
      this.telStatus = arr.length > 0 ? arr[0].deviceStatus : 'idle'
    },
    //拆线
    handleClear(calledDevice, index) {
      let _this = this
      this.currentClear = calledDevice
      this.handleClearConnection(calledDevice)
      store.commit('callFlagEvent', false) // vuex缓存
      //标签页拆线踢出成员
      this.topTitleArr.forEach((e, i) => {
        if (e.isCheck) {
          if (i == 0) {
            return
          } else {
            e.list.forEach((el, num) => {
              if (el.defaultNo == calledDevice) e.list.splice(num, 1)
            })
          }
        }
      })
    },
    //取消
    handleClose() {
      this.selectUserShow = false
      this.selectUsers = []
      this.isCall = true
      this.addBroadMemberBtnShow = false
    },
    //拨号盘呼叫事件
    handleCallMake(calledDevice, type) {
      if (type == 'audio' || type == 'video') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'MakeCall',
            callingDevice: this.callingDevice,
            called: { calledDevice },
            callType: type,
            duplexMode: 'full',
          },
        }).then()
      } else if (type == 'trans') {
        this.handleTransferCall(currentTalkObj.deviceTel, calledDevice)
      } else if (type == 'meeting') {
        //加入会议
        // let item = { realName: calledDevice, defaultNo: calledDevice }
        // this.handleMakeSelect('meetingCall', item)
        this.handleOpenMeeting(calledDevice)
      }
      this.dialDialog = false
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //文件上传回调,
    handleFileCall(fileName) {
      this.broadFileName = fileName
      this.isFileBroad = true
      this.fileDialog = false
    },
    //呼叫保持,解除保持
    handleHoldCall(user) {
      if (user.deviceStatus == 'talk') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'HoldCall',
            calledDevice: user.defaultNo,
            userID: null,
          },
        })
      } else if (user.deviceStatus == 'hold') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'UnHoldCall',
            calledDevice: user.defaultNo,
            userID: null,
            callingDevice: this.callingDevice,
            callType: 'audio',
          },
        })
      } else {
        this.$message.warning('通话类型错误')
        return
      }
    },
    //呼叫保持,解除保持
    handleHoldCallBytel(tel) {
      const status = this.deviceStatusMap.get(tel)
      if (!status) {
        this.$message.warning('用户状态不存在')
        return
      }
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
      if (status == 'talk') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'HoldCall',
            calledDevice: tel,
            userID: null,
          },
        })
      } else if (status == 'hold') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'UnHoldCall',
            calledDevice: tel,
            userID: null,
            callingDevice: this.callingDevice,
            callType: 'audio',
          },
        })
      }
    },
    //呼叫转移,转接
    handleSingleTransferCall(item, type, index) {
      this.thisSelectMember = item
      this.selectTransactionShow = true
      this.transcationTypeFlag = type
      this.getTranscationMember = []
    },
    //选择加入转移转接事件
    handleGetItemforTranscation(item, index) {
      if (item.deviceStatus != 'idle') {
        this.$message.warning(
          this.$i18n.locale == 'en-US'
            ? 'user is not free'
            : '选中用户不是空闲状态'
        )
        return
      }
      this.getTranscationMember = {
        realName: item.realName,
        defaultNo: item.defaultNo,
      }
    },
    //呼叫转移
    handleSingleTransferCallFun() {
      let tel
      if (this.transcationTel) {
        tel = this.transcationTel
      } else {
        if (
          this.getTranscationMember.defaultNo == undefined ||
          this.getTranscationMember.defaultNo == '' ||
          this.getTranscationMember.defaultNo == null
        ) {
          this.$message.warning('选择的转移用户不存在')
          return
        }
        tel = this.getTranscationMember.defaultNo
      }
      if (tel == this.callingDevice) {
        this.$message.warning('选择的转移用户相同')
        return
      }
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'SingleTransferCall',
          activeDevice: this.thisSelectMember.defaultNo,
          called: {
            calledDevice: tel,
            userID: null,
          },
        },
      }).then((res) => {
        if (res.status == 200) {
          this.selectTransactionShow = false
        } else {
          this.$message.warning(
            this.$i18n.locale == 'en-US' ? e.reason : '呼叫转移失败'
          )
          return
        }
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //呼叫转接
    handleTransferCallFun() {
      let tel
      if (this.transcationTel) {
        tel = this.transcationTel
      } else {
        if (
          this.getTranscationMember.defaultNo == undefined ||
          this.getTranscationMember.defaultNo == '' ||
          this.getTranscationMember.defaultNo == null
        ) {
          this.$message.warning('选择的转接用户不存在')
          return
        }
        tel = this.getTranscationMember.defaultNo
      }
      if (tel == this.callingDevice) {
        this.$message.warning('选择的转接用户相同')
        return
      }
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'TransferCall',
          heldDevice: this.thisSelectMember.defaultNo,
          activeDevice: tel,
        },
      }).then((res) => {
        if (res.status == 200) {
          this.selectTransactionShow = false
        } else {
          this.$message.warning('呼叫转接失败')
          return
        }
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //呼叫转移 号码盘
    handleCallMakeTel(tel) {
      this.transcationTel = tel
      this.getTranscationMember = {
        realName: tel,
        defaultNo: tel,
      }
      this.dialDialogTel = false
    },
    /*
     *呼叫转移
     *@parma heldDevice 被转接的用户号码
     *@parma heldDevice 转接的用户号码
     */
    handleTransferCall(heldDevice, activeDevice) {
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'TransferCall',
          heldDevice: heldDevice,
          activeDevice: activeDevice,
        },
      })
    },
    //监听,强拆，强插，强断
    handleForce(item, type) {
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
      makeCall({
        request: {
          '@id': '100000',
          '@type': type,
          callingDevice: this.callingDevice,
          called: { calledDevice: item.defaultNo, userID: null },
        },
      })
    },
    //踢出会议
    handleMeetKick(item) {
      const meetID = this.telMeetingMap.get(item.defaultNo)
      if (meetID == '') {
        this.$message.warning(
          this.$i18n.locale == 'en-US' ? 'please select meeting' : '请选中会议'
        )
        return
      }
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'MeetKick',
          meetID: meetID,
          activeDevice: item.defaultNo,
          userID: null,
        },
      })
    },
    //允许，禁止发言-会议
    handleMeetAllowSpeak(item, type) {
      let typeName
      if (type == 'ban') {
        typeName = 'MeetBanSpeak'
      } else {
        typeName = 'MeetAllowSpeak'
      }
      let meet = this.topTitleArr.filter((e) => {
        return e.isCheck == true
      })
      makeCall({
        request: {
          '@id': '100000',
          '@type': typeName,
          meetID: meet[0].meetID,
          activeDevice: item.defaultNo,
          userID: null,
        },
      })
    },
    //单独通话
    handleMeetSingleTalk(item) {
      const meetID = this.telMeetingMap.get(item.defaultNo)
      if (meetID == '' || meetID == undefined) {
        this.$message.warning(
          this.$i18n.locale == 'en-US' ? 'please select meeting' : '请选中会议'
        )
        return
      }
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'MeetSingleTalk',
          meetID: meetID,
          callingDevice: this.callingDevice,
          activeDevice: item.defaultNo,
          userID: null,
        },
      })
    },
    //回到会场
    handleMeetBack(item) {
      const meetID = this.telMeetingMap.get(item.defaultNo)
      if (meetID == '' || meetID == undefined) {
        this.$message.warning(
          this.$i18n.locale == 'en-US' ? 'please select meeting' : '请选中会议'
        )
        return
      }
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'MeetBack',
          meetID: meetID,
          activeDevice: item.defaultNo,
          userID: null,
        },
      })
    },
    //录音
    handleRecordCall(item, index, isRecord) {
      if (isRecord == 'no') {
        item.isRecord = false
      } else {
        item.isRecord = true
      }
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'RecordCall',
          isRecord: isRecord,
          activeDevice: item.defaultNo,
        },
      }).then((res) => {
        if (res.status == 200) {
          this.$set(this.employeeList, index, item)
        }
      })
    },
    //视频呼叫
    handleMakeCallVideo(calledDevice, name, index, item) {
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'MakeCall',
          callingDevice: this.callingDevice,
          called: { calledDevice },
          callType: 'video',
          duplexMode: 'full',
        },
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //激活遥毙
    handleActivateStun(item, type) {
      //activate:激活，stun:遥毙
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'ActivateStun',
          ActivateMode: type,
          calledDevice: item.defaultNo,
          userID: null,
        },
      })
    },
    //强呼
    handleAdvanceCall(item) {
      let called = []
      item.device.forEach((e) => {
        called.push(e.deviceTel)
      })
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'AdvanceCall',
          callMode: 'parallel',
          callingDevice: this.callingDevice,
          calledDevice: called,
          callType: 'audio',
        },
      })
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
    },
    //群答
    handleGroupAnswerCall() {
      if (this.callinArr.length == 0) {
        this.$message.warning('当前没有呼入电话')
        return
      }
      this.groupOrSelect = 'GroupAnswerCall'
      //打开会议弹窗
      this.handleMakeSelect()
    },
    //跳转到第一标签页
    handleChangeToFirstTitle() {
      this.getChangeTopTitle(this.topTitleArr[0], 0)
    },
    //顶部标签页切换
    getChangeTopTitle(item, index) {
      if (item.isCheck) {
        return
      }
      this.topTitleArr.forEach((e, i) => {
        e.isCheck = false
        if (index == i) {
          e.isCheck = true
          this.titleData = e
        }
      })
      if (index == 0) {
        this.showTree = true
        this.showEmployee = true
        this.showTopTitleDiv = false
      } else {
        this.showTree = false
        this.showEmployee = false
        this.showTopTitleDiv = true
      }
      this.temDataList = this.topTitleArr[index].list
      //更新用户状态
      this.temDataList.forEach((e) => {
        e.deviceStatus = 'idle'
        for (const obj of this.userList) {
          if (obj.deviceTel == e.defaultNo) {
            e.deviceStatus = obj.deviceStatus
            break
          }
        }
      })
      this.showNowStatus = false
    },
    //停止
    handleStopByIsCheck() {
      let _this = this
      store.commit('callFlagEvent', false) // vuex缓存
      for (let i = 0; i < _this.topTitleArr.length; i++) {
        let obj = _this.topTitleArr[i]
        if (obj.isCheck) {
          obj.titleStatus = 'succ'
          if (obj.name == '广播') {
            obj.titleStatusName = obj.name + '完成 ' + this.getNowData()
          } else {
            obj.titleStatusName = obj.name + '失败 ' + this.getNowData()
            obj.list.forEach((e) => {
              if (!e.callStatusName) e.callStatusName = '失败'
            })
          }
          _this.$set(this.topTitleArr, i, obj)
          _this.titleData = obj
          break
        }
      }
      const obj = _this.titleData
      if (obj.name == '组呼') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'EndGroupCall',
            flowID: obj.flowID,
          },
        })
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'MeetKick',
            meetID: obj.meetID,
            activeDevice: null,
            userID: null,
          },
        })
      } else if (obj.name == '选呼') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'EndSelectCall',
            flowID: obj.flowID,
          },
        })
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'MeetKick',
            meetID: obj.meetID,
            activeDevice: null,
            userID: null,
          },
        })
      } else if (obj.name == '广播') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'EndBroadcastCall',
            flowID: obj.flowID,
          },
        })
      } else if (obj.name == '轮询') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'EndPollCall',
            flowID: obj.flowID,
          },
        })
      } else if (obj.name == '点名') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'EndRollCall',
            flowID: obj.flowID,
          },
        })
      }
      //
    },
    //关闭标签页
    handleCloseByIsCheck() {
      const obj = this.topTitleArr.filter((e) => {
        return e.isCheck == true
      })
      if (obj.length == 0) {
        this.$message.warning('error')
        return
      }
      let title = obj[0]
      title.isShow = false
      title.list = []
      this.showTree = true
      this.showEmployee = true
      this.showTopTitleDiv = false
      this.topTitleArr.filter((e, index) => {
        if (e.isCheck == true) {
          e.isClose = true
        }
        e.isCheck = false
        if (index == 0) {
          e.isCheck = true
        }
      })
      //关闭
      const titleName = this.titleData.name
      for (let i = 0; i < this.topTitleArr.length; i++) {
        this.topTitleArr[i].isCheck = false
        if (i == 0) {
          this.topTitleArr[i].isCheck = true
        }
      }
      this.openFirstTopTitle()
      //如果是会议，关闭会场
      if (title.name == 'meeting') {
        SDK.meetKick(title.meetID).then((res) => {})
      }
    },
    //打开通话详情
    openRecordDetial(item, index) {
      this.record_list.forEach((e, i) => {
        if (index != i) e.isOpen = false
      })
      item.isOpen = !item.isOpen
      this.$set(this.record_list, index, item)
    },
    //打开广播加入成员
    addBroadMember() {
      //当前选中的广播de flowID--加入成员时使用
      this.topTitleArr.forEach((e, index) => {
        if (e.isCheck) this.thisChooseBroadFlowID = e.flowID
      })
      this.topTitleArr.forEach((e, index) => {
        e.isCheck = false
        if (index == 0) e.isCheck = true
      })
      this.moreShow = false
      this.selectUserShow = true
      this.isCall = false
      this.rollCallBtnShow = false
      this.selectBtnShow = false
      this.pollBtnShow = false
      this.showTree = true
      this.showEmployee = true
      this.showTopTitleDiv = false
      this.addBroadMemberBtnShow = true
      this.selectUsers = []
      this.broadBtnShow = false
    },
    //广播加入成员
    handleAddBroadMember() {
      let _this = this
      this.showBroadDialog = false
      const called = this.selectUsers.map((e) => ({
        calledDevice: e.calledDevice,
        userID: null,
      }))
      _this.topTitleArr.forEach((e) => {
        if (e.flowID == _this.thisChooseBroadFlowID) {
          e.list = e.list.concat(this.selectUsers)
          _this.temDataList = e.list
        }
      })
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'BroadcastCall',
          callingDevice: this.callingDevice,
          called,
          callMode: this.thisBroadType,
          time: null,
          callLoop: 0,
          fileName: this.broadFileName,
          flowID: this.broadID,
        },
      })
      this.topTitleArr.forEach((e) => {
        e.isCheck = false
        if (e.name == '广播') e.isCheck = true
      })
      this.addBroadMemberBtnShow = false
    },
    //封装-打开到第一标签页
    openFirstTopTitle() {
      this.showTree = true
      this.showEmployee = true
      this.showTopTitleDiv = false
    },
    //封装-更新标签页发起成员失败状态
    updateMemberFailStatus(e) {
      if (e.eventdata.calledResult == 'fail') {
        this.topTitleArr.forEach((el) => {
          if (el.flowID == e.eventdata.flowID) {
            el.list.forEach((element) => {
              if (element.defaultNo == e.eventdata.calledDevice)
                element.callStatusName = '失败'
              element.realName = element.realName + ' '
            })
          }
        })
      }
      this.showTree = false
      this.showEmployee = false
      this.showTopTitleDiv = true
      // this.showNowStatus = false
    },
    //封装-更新标签页发起成员失败/成功状态
    updateMemberFailOrSuccStatus(e) {
      if (e.eventdata.calledResult == 'fail') {
        this.topTitleArr.forEach((el) => {
          if (el.flowID == e.eventdata.flowID) {
            el.list.forEach((element) => {
              if (element.defaultNo == e.eventdata.calledDevice)
                element.callStatusName = '失败'
            })
          }
        })
      } else if (e.eventdata.calledResult == 'succ') {
        this.topTitleArr.forEach((el) => {
          if (el.flowID == e.eventdata.flowID) {
            el.list.forEach((element) => {
              if (element.defaultNo == e.eventdata.calledDevice)
                element.callStatusName = '成功'
            })
          }
        })
      }
      this.showTree = false
      this.showEmployee = false
      this.showTopTitleDiv = true
      this.selectUserShow = false
    },
    //接听/拒绝接听(应答，拆线)
    handleAccpet(type, tel) {
      if (type == 'accept') {
        makeCall({
          request: {
            '@id': '100000',
            '@type': 'AnswerCall',
            callingDevice: this.callingDevice,
            calledDevice: tel,
            userID: null,
          },
        }).then((res) => {})
        store.commit('callFlagEvent', true) // vuex缓存
        window.handlePlayDialt('pause')
      } else {
        this.handleClearConnection(tel)
        store.commit('callFlagEvent', false) // vuex缓存
      }
    },
    //读取txt内容
    uploadPrivateKey() {
      const privateKeyFile = this.$refs.uploads.files[0]
      let reader = new FileReader()
      if (typeof FileReader === 'undefined') {
        this.$message({
          type: 'info',
          message: '您的浏览器不支持FileReader接口',
        })
        return
      }
      reader.readAsText(privateKeyFile, 'utf-8')
      var _this = this
      reader.onload = function (e) {
        console.log('文本文件内容')
        console.log(e.target.result)
        _this.textarea = e.target.result
        _this.textareaNum = e.target.result.length
      }
    },
    //读取文字广播字数
    getNumOfTextarea() {
      this.textareaNum = this.textarea.length
    },
    //获取缓存数据
    getSessionStoreData() {
      //获取缓存数据
      let linkDevice = sessionStorage.getItem('linkDevice')
      let topTitleArr = sessionStorage.getItem('topTitleArr')
      let talkArr = sessionStorage.getItem('talkArr')
      let missArr = sessionStorage.getItem('missArr')
      let camaraBoxData = sessionStorage.getItem('phone_linked_video_play_data')
      this.linkDevice =
        linkDevice != '' && linkDevice != undefined ? linkDevice : ''
      this.topTitleArr =
        topTitleArr == null ? this.topTitleArr : JSON.parse(topTitleArr)
      this.topTitleArr.forEach((e, index) => {
        e.isCheck = false
        if (index == 0) e.isCheck = true
      })
      this.talkArr = talkArr == null ? [] : JSON.parse(talkArr)
      this.missArr = missArr == null ? [] : JSON.parse(missArr)
      camaraBoxData = camaraBoxData == null ? [] : JSON.parse(camaraBoxData)
    },
    //打开软电话视频video
    handleOpenWebrtcVideo() {
      let _this = this
      let webrtc2Sip = Webrtc2Sip.getWebrtc2SipByName(this.callingDevice)
      if (webrtc2Sip) {
        // webrtc2Sip.playVideo()
      } else {
        console.log('软电话注册失败')
      }
    },
    //关闭广播
    handleCloseBroad(flowID) {
      makeCall({
        request: {
          '@id': '100000',
          '@type': 'EndBroadcastCall',
          flowID: flowID,
        },
      })
    },
    //判断配置的话机
    handleGetPhoneType() {
      if (this.operatorInfo.mainTelType == 'phone') {
        this.handleToggleTel(true)
      } else if (this.operatorInfo.viceTelType == 'phone') {
        this.handleToggleTel(false)
      }
      this.handleOpenDispatchgroup()
    },
    //搜索
    handleSearch() {
      if (this.input == '') {
        this.$message.warning(this.$t('m.tip.PLEASE_ENTER_CONTENT'))
        return
      }
      const inputData = this.input
      let searchData = []
      this.employeeMap.forEach((e) => {
        e.deviceStatus = 'idle'
        if (e.status) {
          e.deviceStatus = e.status
        }
        if (e.realName.indexOf(inputData) > -1) {
          searchData.push(e)
          return true
        }
        for (let i = 0; i < e.device.length; i++) {
          let device = e.device[i]
          if (device.deviceTel.indexOf(inputData) > -1) {
            searchData.push(e)
            break
          }
        }
      })
      this.operatorMap.forEach((e) => {
        e.deviceStatus = 'idle'
        if (e.status) {
          e.deviceStatus = e.status
        }
        if (
          e.realName.indexOf(inputData) > -1 ||
          e.mainTel.indexOf(inputData) > -1 ||
          e.viceTel.indexOf(inputData) > -1
        ) {
          //构造
          let user = this.handleMakeUserCardData(e.mainTel)
          searchData.push(user)
          return true
        }
      })
      this.topTitleArr.forEach((e) => {
        e.isCheck = false
      })
      let title = this.topTitleArr[2]
      title.isShow = true
      title.isCheck = true
      title.titleStatusName = '搜索结果(' + inputData + ') ' + this.getNowData()
      title.list = searchData
      title.titleStatus = 'succ'
      this.titleData = deepClone(title)
      this.showTree = false
      this.showEmployee = false
      this.showTopTitleDiv = true
      this.selectUserShow = false
      this.temDataList = searchData
    },
    //默认选中调度组
    handleOpenDispatchgroup() {
      let id = ''
      this.groupMap.forEach((e) => {
        if (e.obj.groupType == 'dispatchgroup') {
          id = e.id
          return true
        }
      })
      if (id == '') {
        return
      }
      let obj = this.groupMap.get(id)
      if (obj == undefined || obj == null) {
        return
      }
      this.expandedTreeKey.push(obj.parentID)
      this.$nextTick(function () {
        let node = this.$refs.tree.getNode(id)
        if (node) {
          this.$refs.tree.setCurrentKey(id)
          this.handleSelectGroup(node.data)
        }
      })
    },
    //点击切换背景色
    changeBackgroudColor(type) {
      if (type == 'down') {
        this.HangupImg = require('../../assets/images/Hangup_Hover.png')
      } else {
        this.HangupImg = require('../../assets/images/Hangup.png')
      }
    },
    //构造职员卡片内容
    handleMakeUserCardData(tel) {
      let emp = deepClone(this.telEmployeeMap.get(tel))
      if (emp) {
        emp.startTime = new Date()
      }
      if (!emp) {
        let memberData = this.telOperatorMap.get(tel)
        if (!memberData) {
          return ''
        }
        emp = {
          defaultNo: memberData.mainTel,
          realName: memberData.realName,
          order: memberData.orderNO,
          telType: memberData.mainTelType == 'phone' ? '话机' : '手咪',
          myDutyName: '调度员',
          groupName: memberData.groupName,
          startTime: new Date(),
          group: [{ groupID: memberData.groupID }],
          device: [
            {
              deviceTel: memberData.mainTel,
              deviceType: memberData.mainTelType,
              isCheck: true,
            },
            {
              deviceTel: memberData.viceTel,
              deviceType: memberData.viceTelType,
              isCheck: false,
            },
          ],
        }
      }
      if (!emp.myDutyName) {
        emp.myDutyName = emp.dutyName.length > 0 ? emp.dutyName[0] : '无职务'
      }
      emp.device.forEach((el, index) => {
        el.isCheck = false
        if (emp.defaultNo == el.deviceTel) {
          el.isCheck = true
        }
      })
      emp.deviceStatus = 'idle' //默认空闲
      emp.isRecord = true //默认开启录音
      const status = this.deviceStatusMap.get(emp.defaultNo)
      if (status) {
        emp.deviceStatus = status
      }
      const empdata = { ...emp }
      return empdata
    },
    //职员加入正在通话
    handleJoinTalkArr(tel) {
      let emp = this.handleMakeUserCardData(tel)
      if (emp) {
        let i = this.talkArr.filter((e) => {
          return e.defaultNo == emp.defaultNo
        }).length
        if (i == 0) {
          emp = deepClone(emp)
          emp.deviceStatus = 'callin'
          emp.realNameAndDefoutNo = this.getTalkArrRealNameAndDefoutNo(emp)
          let groupName = ''
          emp.group.forEach((element, index) => {
            const group = this.groupMap.get(element.groupID)
            if (index != 0) {
              groupName = groupName + ','
            }
            groupName = groupName + group.label
          })
          emp.groupName = groupName
          this.talkArr.push(emp)
        }
      }
    },
    //职员退出正在通话,等待列表，保持列表
    handleExitTalkArr(tel) {
      this.talkArr = this.talkArr.filter((e) => {
        return e.defaultNo != tel
      })
      this.callinArr = this.callinArr.filter((e) => {
        return e.deviceTel != tel
      })
      this.keepList = this.keepList.filter((e) => {
        return e.deviceTel != tel
      })
    },
    //职员退出保持列表
    handleExitKeepList(tel) {
      this.keepList = this.keepList.filter((e) => {
        return e.deviceTel != tel
      })
    },
    //通话时间记录定时器
    talkTimer() {
      if (this.telStatus == 'idle') {
        this.talkArr = []
      }
      if (this.talkArr.length > 0) {
        this.talkArr.forEach((e, index) => {
          let obj = this.getRunTimeByObject(e)
          this.$set(this.talkArr, index, obj)
        })
      }
      if (this.callinArr.length > 0) {
        this.callinArr.forEach((e, index) => {
          let obj = this.getRunTimeByObject(e)
          this.$set(this.callinArr, index, obj)
        })
      }
      if (this.currentTalkObj) {
        let obj = this.getRunTimeByObject(this.currentTalkObj)
        this.currentTalkObj = deepClone(obj)
      }
      if (this.keepList.length > 0) {
        this.keepList.forEach((e, index) => {
          let obj = this.getRunTimeByObject(e)
          this.$set(this.keepList, index, obj)
        })
      }
    },
    //给对象中数据计算持续时间
    getRunTimeByObject(obj) {
      if (obj.startTimeString == null || obj.startTimeString == undefined) {
        return obj
      }
      let talkTime = CalculateTime(obj.startTime)
      if (talkTime == 'NaN:NaN:NaN') {
        return obj
      }
      obj.talkTime = talkTime
      return obj
    },
    //判断当前标题页,并赋值成功
    handleGetCurremtTitleIndex(flowID) {
      let _this = this
      for (let i = 0; i < _this.topTitleArr.length; i++) {
        let obj = _this.topTitleArr[i]
        if (flowID == obj.flowID) {
          if (obj.name == '广播') {
            obj.titleStatusName = obj.name + '开始时间 ' + this.getNowData()
          } else {
            obj.titleStatus = 'succ'
            obj.titleStatusName = obj.name + '完成 ' + this.getNowData()
          }
          _this.$set(this.topTitleArr, i, obj)
          if (obj.isCheck) {
            _this.titleData = obj
          }
          break
        }
      }
    },
    //获取当前时间
    getNowData() {
      var myDate = new Date()
      var hours = myDate.getHours()
      if (hours < 10) {
        hours = '0' + hours
      }
      var min = myDate.getMinutes()
      if (min < 10) {
        min = '0' + min
      }
      var sec = myDate.getSeconds()
      if (sec < 10) {
        sec = '0' + sec
      }
      return hours + ':' + min + ':' + sec
    },
    //转到会议
    handleChangeToMeeting() {
      this.$router.push({ name: 'meeting' })
    },
    //呼叫保持拆线
    handleStopHold() {
      this.handleClearConnection(this.callingDevice)
      store.commit('callFlagEvent', false) // vuex缓存
    },
    //得到当前通话对象realName,defoutNo
    getTalkArrRealNameAndDefoutNo(item) {
      let name = item.realName + ' ' + item.defaultNo
      return name
    },
    //加入到未接来电
    handleJoinMissCall(item) {
      if (item == undefined) {
        return
      }
      item.beginTime = this.getNowData()
      item.isOpen = false
      this.missArr.push(item)
      // this.missArr.reverse()
      let arr = this.missArr.sort(function (a, b) {
        let at = a.beginTime.replace(':', '').replace(':', '')
        let bt = b.beginTime.replace(':', '').replace(':', '')
        return bt - at
      })
      this.missArr = arr
    },
    //用户拨打调度台挂断事件
    handleMissArr(e) {
      //呼入电话中存在，加入未接来电
      let misscallArr = this.callinArr.filter((deviceTel) => {
        return deviceTel.deviceTel == e.deviceTel
      })
      if (misscallArr && misscallArr.length > 0) {
        let missCall = misscallArr[0]
        this.handleJoinMissCall(missCall)
        //呼入电话移除
        this.callinArr = this.callinArr.filter((e) => {
          return e.deviceTel != missCall.deviceTel
        })
      }
    },
    //加入呼入电话
    handleCallin(callinDevice) {
      if (callinDevice == this.calledDevice) {
        return
      }
      let flag = this.callinArr.some((callin) => {
        return callin.deviceTel == callinDevice
      })
      if (flag) {
        return
      }
      const obj = this.makeCurrentTalkObj(callinDevice)
      this.callinArr.push(obj)
      this.currentTalkObj = deepClone(obj)
    },
    //构造当前通话对象
    makeCurrentTalkObj(callinDevice) {
      let emp = this.telEmployeeMap.get(callinDevice)
      let obj = {
        deviceTel: callinDevice,
        realName: emp ? emp.realName : '',
        groupName: emp ? this.getGroupNameByGroupId(emp.group[0].groupID) : '',
        isCheck: false,
        startTime: new Date(),
        startTimeString: this.getNowData(),
      }
      return obj
    },
    //加入保持列表
    handleAddKeepList(callinDevice) {
      if (callinDevice == this.calledDevice) {
        return
      }
      let emp = this.telEmployeeMap.get(callinDevice)
      let obj = {}
      if (emp) {
        obj = {
          deviceTel: callinDevice,
          realName: emp.realName,
          groupName: this.getGroupNameByGroupId(emp.group[0].groupID),
          isCheck: false,
          startTime: new Date(),
          startTimeString: this.getNowData(),
        }
      } else {
        obj = {
          deviceTel: callinDevice,
          isCheck: false,
          startTime: new Date(),
          startTimeString: this.getNowData(),
        }
      }
      this.keepList.push(obj)
    },
    //监听鼠标点击事件
    addEventListenerFun() {
      let _this = this
      document.addEventListener('click', function (e) {
        var more = document.getElementById('more')
        var moreButton = document.getElementById('moreButton')
        var searchButton = document.getElementById('searchButton')
        var searchDiv = document.getElementById('searchDiv')
        if (
          more &&
          moreButton &&
          !more.contains(e.target) &&
          !moreButton.contains(e.target)
        ) {
          _this.moreShow = false
        }
      })
    },
    //修改职员信息后，刷新数据
    handleUpdateData() {
      let node = this.$refs.tree.getCurrentNode()
      this.handleSelectGroup(node)
    },
    //分页加载通话记录
    loadMoreRecord() {
      if (this.right_text != '通话记录') {
        return
      }
      this.recordListQuery.beginIndex = this.recordListQuery.beginIndex + 20
      getCallrecord(this.recordListQuery).then((res) => {
        const list = res.data.record_list
        this.record_list = this.record_list.concat(list)
      })
    },
    //打开定时广播
    handleTimeBroadcast() {
      this.timeBroadcastDialog = true
      this.moreShow = false
    },
    //打开广播模式选择
    handleOpenBroadcast() {
      this.broadcastForm = {
        callMode: 'manual',
        type: '0', //0循环，1次数
        num: '1',
      }
      this.showBroadDialog = true
    },
    //选择广播模式
    handleMakeBroadcastType() {
      let callMode = this.broadcastForm.callMode
      if (callMode == 'file' || callMode == 'tts') {
        if (this.broadcastForm.type == 1) {
          if (this.broadcastForm.num == '') {
            return this.$message.error('请填写广播次数')
          }
        }
      }
      if (callMode == 'manual') {
        this.handleBroadManual()
      } else if (callMode == 'file') {
        this.handleFileBroad()
      } else if (callMode == 'tts') {
        this.handleTextBroad()
      }
    },
    // 打开视频分发窗口
    openVideoDistribution(data) {
      console.log('视频分发')
      this.distributionSource = data
      this.openDistribution = true
    },
    fullScreen() {},
    //根据groupId获取组名
    getGroupNameByGroupId(id) {
      const group = this.groupMap.get(id)
      if (group) {
        return group.label
      }
      return ''
    },
    //获取当前用户状态
    getUserStatusBytel(tel) {
      if (tel == '' || tel == undefined) {
        return
      }
      const deviceStatus = this.deviceStatusMap.get(tel)
      if (deviceStatus) {
        return this.$t('m.dict.callStatus')[deviceStatus].text
      }
      return ''
    },
    //打开会议标签页
    handleOpenMeeting(calledDevice) {
      const flag = this.topTitleArr[1].isShow
      if (flag) {
        //切换到会议标签页
        this.getChangeTopTitle(deepClone(this.topTitleArr[1]), 1)
        if (!calledDevice) {
          return
        }
      }
      this.topTitleArr.forEach((e) => {
        e.isCheck = false
      })
      SDK.getMeetingList().then((res) => {
        let meet_list = res.meet_list
        meet_list = meet_list.filter((e) => {
          return e.meetMode == 'audio'
        })
        if (meet_list.length == 0) {
          return this.$message.error('语音会议数量为0')
        }
        const meetID = meet_list[0].meetID
        let title = this.topTitleArr[1]
        title.isShow = true
        title.isCheck = false
        title.titleStatus = 'succ'
        title.meetID = meetID
        //切换到会议标签
        this.getChangeTopTitle(deepClone(title), 1)
        //会议加入成员、
        if (calledDevice) {
          this.meetingJoinUser(calledDevice)
        }
      })
    },
    //成员加入会议
    meetingJoinUser(calledDevice) {
      store.commit('callFlagEvent', true) // vuex缓存
      window.handlePlayDialt('pause')
      const meetID = this.topTitleArr[1].meetID
      SDK.meetingCall(meetID, [calledDevice], this.callingDevice)
      let user = this.handleMakeUserCardData(calledDevice)
      //判断本人是否在会议中，不在就加入
      let userList = this.topTitleArr[1].list
      const result = userList.some((e) => {
        return e.defaultNo == this.callingDevice
      })
      if (!result) {
        let myInfo = this.handleMakeUserCardData(this.callingDevice)
        userList.push(myInfo)
      }
      userList.push(user)
      this.$set(this.topTitleArr, 1, deepClone(this.topTitleArr[1]))
    },
    //等待队列操作事件
    handleWaitListDo(command, row) {
      switch (command) {
        case 'accept':
          //应答
          this.handleAccpet('accept', row.deviceTel)
          break
        case 'unAccept':
          //拒接
          this.handleAccpet('unAccept', row.deviceTel)
          break
      }
    },
    //保持队列操作事件
    handleKeepListDo(command, row) {
      switch (command) {
        case 'unHold':
          const status = this.getUserStatusBytel(this.currentTalkObj.deviceTel)
          if (status === 'talk') {
            this.$message.error(this.$t('m.tip.PLEASE_END_THE_CURRENT_CALL'))
            return
          }
          //解除保持
          this.handleHoldCallBytel(row.deviceTel)
          break
        case 'off':
          //挂断
          this.handleClearConnection(row.deviceTel)
          break
        case 'joinMeet':
          this.handleOpenMeeting(row.deviceTel)
          break
      }
    },
    //获取操作员状态图片
    getOperatorPic(operator) {
      const mainTel = operator.mainTel
      const status = this.deviceStatusMap.get(mainTel)
      if (status) {
        return this.$t('m.dict.callStatusAll')[status].pic
      }
      return require('@/assets/images/idle.png')
    },
    //总机代答
    totalAnswer(operator) {
      if (this.operatorInfo.agentState != 'login') {
        return this.$message.error(this.$t('m.tip.PLEASE_KAIBAN'))
      }
      let linkDevice = this.deviceLinkMap.get(operator.mainTel)
      this.handleAccpet('accept', linkDevice)
    },
    //咨询后，同意转接
    handleTransferCallAfterConsult() {
      let form = this.currentTalkObj.consultForm
      SDK.transferCall(form)
      delete this.currentTalkObj.form
    },
    //咨询后，拒接转接
    handleClearAfterConsult() {
      let form = this.currentTalkObj.consultForm
      this.handleClearConnection(form.heldDevice)
      delete this.currentTalkObj.form
    },
  },
  mounted() {
    var _this = this
    SDK.setEvent(this.event)
    getOperator().then((res) => {
      userStatus({ deviceTel: 'all' }).then((result) => {
        const { mainTel } = res.data.eventdata
        this.userList = result.data.userList
        const arr = result.data.userList.filter((e) => e.deviceTel == mainTel)
        this.telStatus = arr.length > 0 ? arr[0].deviceStatus : 'idle'
      })
    })
    setTimeout(() => {
      this.setWebrtcCostumEvent()
      this.handleGetPhoneType()
    }, 1000)
    this.getSessionStoreData()
    this.timer = setInterval(() => {
      this.talkTimer() // 修改数据date
    }, 1000)
    //监听点击事件
    this.addEventListenerFun()
    this.fiterUserGroupTreeData()
    //定义全局函数
    window['handleLocalPhoneAccept'] = (res) => {
      this.handleLocalPhoneAccept.call(this, res)
    }
    this.init()
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    if (to.fullPath != '/phone') {
      sessionStorage.setItem('talkArr', JSON.stringify(this.talkArr))
      sessionStorage.setItem('topTitleArr', JSON.stringify(this.topTitleArr))
      sessionStorage.setItem('missArr', JSON.stringify(this.missArr))

      if (this.timer) {
        clearInterval(this.timer)
      }
      let webrtc2Sip = Webrtc2Sip.getWebrtc2SipByName(this.callingDevice)
      if (webrtc2Sip) {
        console.log('clearCustomEvent')
        webrtc2Sip.clearCustomEvent()
      }
    }
    next()
  },
}
</script>

<style lang="scss" scope>
@import '~@/assets/scss/meeting_propper.scss';
@import '~@/assets/scss/phone.scss';
@import '~@/assets/scss/meeting.scss';
</style>